﻿#include "detection.h"
#include "ui_detection.h"

#include <QFileDialog>
#include<QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include<QLibrary>
#include<QChar>
#include"uploadimage.h"
#include"waiting.h"
#include<QFuture>
#include"titlebar.h"
#include <QtConcurrent>
typedef int (*ptrSub2)(const char*,const char*); //定义函数指针

typedef int(*ptrSub)(int, int);

//字符编码设为utf-8
//#pragma execution_character_set("utf-8")



detection::detection(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::detection)
{
    //设置无边框
    this->setWindowFlags(Qt::FramelessWindowHint);


    ui->setupUi(this);
    ui->label_image->setFrameShape (QFrame::Box);
    ui->label_image->setStyleSheet("border-width: 1px;border-style: solid;border-color: rgb(255, 170, 0);");
    //    ui->label_real_username->setText(QString(login::Qname));//右上角的名字
    //ui->label_real_username->setText(QStringLiteral("张三"));//右上角的名字
    //设置窗口图标
    //    this->setWindowIcon(QIcon(":/images/软件图标.png"));

    //建立connect，不必放到构造函数
    //    res=new result;
    //    connect(this,SIGNAL(sendData(QString,QString,bool)),res,SLOT(getOutputImageName(QString,QString,bool)));




}

detection::~detection()
{
    delete ui;

}

void detection::on_pushButton_upload_clicked()
{
    fileNameList.clear();
    imageNameList.clear();
    //多文件替换
    fileNameList=QFileDialog::getOpenFileNames(this,
                                               tr("open iamge"),//对话框名称
                                               ".",//默认打开文件位置“.”文件目录"/"根目录
                                               tr("image files(*.jpg *.png)"));//筛选器


    //    fileName = QFileDialog::getOpenFileName(this,
    //                                            tr("open iamge"),//对话框名称
    //                                            ".",//默认打开文件位置“.”文件目录"/"根目录
    //                                            tr("image files(*.jpg *.png)"));//筛选器


    //多图片信息获取名称
    QFileInfo fileInfoTemp;
    for(int i=0;i<fileNameList.size();i++){
        fileInfoTemp=QFileInfo(fileNameList[i]);
        imageNameList.append(fileInfoTemp.fileName());
        qDebug()<<"file:"<<imageNameList[i];
    }

    //    //图片信息
    //    QFileInfo fileInfo=QFileInfo(fileName);
    //    //图片名称
    //    imageName=fileInfo.fileName();
    if(fileNameList.size()==0){
        QMessageBox::warning(NULL,QStringLiteral("图像选择失败"),QStringLiteral("请选择图片"));
        //清空图片选区
        ui->label_image->clear();
        ui->label_image->setText(QStringLiteral("图片展示"));

    }
    else {
        QImage* img=new QImage;
        if(!(img->load(fileNameList[0]))) //加载图像
        {
            QFile file(fileNameList[0]);
            if(!file.open(QIODevice::ReadOnly))
            {
                QMessageBox::warning(NULL,QStringLiteral("图像选择失败"),QStringLiteral("请选择图片"));

            }
            else {
                //强制加载图片
                img->loadFromData(file.readAll());
                ui->label_image->setScaledContents(true);
                //      ui->label_image->setPixmap(QPixmap::fromImage((*img)));
                //QLable的拉伸策略
                ui->label_image->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored);
                ui->label_image->setPixmap(QPixmap::fromImage((*img)).scaled(ui->label_image->width(),
                                                                             ui->label_image->height(),
                                                                             Qt::KeepAspectRatio,
                                                                             Qt::SmoothTransformation));
            }
        }
        else{
            ui->label_image->setScaledContents(true);
            //QLable的拉伸策略
            ui->label_image->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored);
            ui->label_image->setPixmap(QPixmap::fromImage((*img)).scaled(ui->label_image->width(),
                                                                         ui->label_image->height(),
                                                                         Qt::KeepAspectRatio,
                                                                         Qt::SmoothTransformation));
        }
        delete img;


    }


}
//点击检测
void detection::on_pushButton_detect_by_click_clicked()
{
     qDebug() << QStringLiteral("结果界面的个数：")<<fileNameList.size();

     //输出路径
     QString temp_path= setting::downloadPath+"/temp";
     this->makeDirPath(temp_path);

     std::string output_dir0=temp_path.toStdString();
     const char* output_dir=output_dir0.c_str();

     qDebug() << QStringLiteral("output路径：")<<output_dir;
    if(fileNameList.size()==0){
        QMessageBox::warning(NULL,QStringLiteral("图像检测失败"),QStringLiteral("未检测到图片"));

    }
    else {
        qDebug() << QStringLiteral("dll加载中");
        QLibrary mylib("main");//加载dll
        if(mylib.load())
        {
            qDebug() << QStringLiteral("dll加载成功");
            ptrSub2 main_test1 = (ptrSub2)mylib.resolve("main_test");

            if(main_test1!=NULL)
            {
                qDebug() << QStringLiteral("dll检测函数加载成功");
                for(int i=0;i<fileNameList.size();i++){
                    result*res=new result;

                    std::string str = fileNameList[i].toStdString();
                    const char* image_file=str.c_str();
                    //加载等待界面
                    Waiting pWait(this);
                    pWait.show();
                    QFuture<int> fut=QtConcurrent::run([=]()->int{ return main_test1(image_file,output_dir);}); //异步处理
                    while(!fut.isFinished())
                    {
                        QApplication::processEvents(QEventLoop::AllEvents, 100);//唤醒主界面
                    }
                    int num=fut.result();
                    //结束等待界面
                    pWait.close();

                    //不断保持这个
//                    qApp->processEvents();

                    qDebug()<<QStringLiteral("检测到的个数")<<num;


                    outputImageName=temp_path+"/"+imageNameList[i];
                    qDebug()<<QStringLiteral("detection: picture->")+outputImageName;
                    QString message=QStringLiteral("检测到")+QString::number(num)+QStringLiteral("个结直肠息肉");
//                    qDebug()<<QStringLiteral("qRes.at(i)")<<qRes.at(i);

                    connect(this,SIGNAL(sendData(QString,QString,bool)),res,SLOT(getOutputImageName(QString,QString,bool)));

                    //传输到结果界面
                    emit sendData(outputImageName,message,true);
                    //断联
                    disconnect(this,SIGNAL(sendData(QString,QString,bool)),res,SLOT(getOutputImageName(QString,QString,bool)));

                    //自定义标题栏
                    TitleBar*tBar=new TitleBar;

                    tBar->setAttribute(Qt::WA_DeleteOnClose, true);
                    tBar->setMainWidget(res);
                    tBar->setTitleBarText(QStringLiteral("检测结果"));
                    tBar->show();

                }
            }
            else{
                qDebug() << QStringLiteral("dll检测函数加载失败");
            }

        }
        else{
            qDebug() << QStringLiteral("dll检测函数加载失败");
        }
    }
}

//创建文件夹嘛
void detection::makeDirPath(QString dirPath)
{
    QString dest=dirPath;
    QDir dir;
    if(!dir.exists(dest))
    {
        dir.mkpath(dest);
    }
}
